package com.zx.tradeclient.ctrl.index4;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zx.base.ctrl.BaseActivity;
import com.zx.base.ctrl.Constant;
import com.zx.base.http.HttpUtils;
import com.zx.base.http.HttpUtils.CallBack;
import com.zx.base.lazylist.ImageLoader;
import com.zx.base.util.ActivityTaskManager;
import com.zx.base.util.URLHelper;
import com.zx.base.widget.ExpanderDialog;
import com.zx.base.widget.ExpanderDialog.DialogListener;
import com.zx.base.widget.LoadMoreListView;
import com.zx.base.widget.LoadMoreListView.OnLoadMoreListener;
import com.zx.base.widget.LoadMoreListViewWithProgress;
import com.zx.base.widget.QuitDialog;
import com.zx.tradeclient.R;
import com.zx.tradeclient.adapter.ProductPageAdapter;
import com.zx.tradeclient.app.TradeApp;
import com.zx.tradeclient.ctrl.SearchActivity;
import com.zx.tradeclient.entity.ProductItemInfo;

public class Index4Activity extends BaseActivity implements OnClickListener {
	/** Called when the activity is first created. */

	private Button header_left, header_right;
	private ProductPageAdapter adapter;
	private ArrayList<ProductItemInfo> list_info = new ArrayList<ProductItemInfo>();
	private TradeApp app;

	private LoadMoreListViewWithProgress viewWhitProgress;
	private LoadMoreListView listView;
	private int currentPage;
	private int totalPage;
	private static int currentItem = 0; // 当前图片的索引号
	private int perPageCount = 14;
	private ImageLoader imageLoader;
	private LinearLayout linear;
	private ExpanderDialog expander;
	private static Header header;
	private ArrayList<String> mHeaerID = new ArrayList<String>();

	private class Header {
		private ViewPager viewPager; // android-support-v4中的滑动组件
		private List<ImageView> imageViews; // 滑动的图片集合
		private String[] titles; // 图片标题
		private int[] imageResId; // 图片ID
		private List<View> dots; // 图片标题正文的那些点
		private TextView tv_title;
		private TopAdapter topadapter;

		private ScheduledExecutorService scheduledExecutorService;// 切换当前显示的图片
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				loadDataTask();
				break;
			case 1:

				adapter.notifyDataSetChanged();

				break;
			case 2:

				Toast toast2 = Toast.makeText(Index4Activity.this, "无反应",
						Toast.LENGTH_SHORT);
				toast2.setGravity(Gravity.CENTER, 0, 0);
				toast2.show();

				break;
			case 3:
				header.viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
				break;
			default:
				;
				break;

			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index4);

		if (!(ActivityTaskManager.getInstance().containsName("Index4Activity"))) {
			ActivityTaskManager.getInstance().putActivity("Index4Activity",
					this);
		}

		init();

	}

	@Override
	public void onResume() {
		// 继续滚动
		startTop();
		super.onResume();
	}

	@Override
	public void onPause() {
		// 停滚
		stopTop();
		super.onPause();
	}

	public void startTop() {
		header.scheduledExecutorService = Executors
				.newSingleThreadScheduledExecutor();
		if (Constant.debug)
			Log.d("TAG", "开始了亲");
		// 当Activity显示出来后，每两秒钟切换一次图片显示
		header.scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(),
				0, 3, TimeUnit.SECONDS);
	}

	public void stopTop() {
		// 当Activity不可见的时候停止切换
		header.scheduledExecutorService.shutdown();
	}

	/**
	 * 换行切换任务
	 * 
	 * @author Administrator
	 * 
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (header.viewPager) {
				System.out.println("currentItem: " + currentItem);
				currentItem = (currentItem + 1) % header.imageResId.length;
				Message msg = new Message();
				msg.what = 3;
				handler.sendMessage(msg);
			}
		}

	}

	private void init() {

		app = (TradeApp) getApplication();
		imageLoader = app.imageLoader;
		header_left = (Button) findViewById(R.id.header_left);
		header_left.setBackgroundResource(R.drawable.header_dquery);
		header_left.setOnClickListener(this);

		header_right = (Button) findViewById(R.id.header_right);
		header_right.setBackgroundResource(R.drawable.header_dnone);
		header_right.setText("等级");
		header_right.setOnClickListener(this);

		linear = (LinearLayout) findViewById(R.id.index4_linear);

		adapter = new ProductPageAdapter(Index4Activity.this, list_info,
				app.imageLoader);

		viewWhitProgress = new LoadMoreListViewWithProgress(this);
		listView = viewWhitProgress.getListView();

		header = new Header();
		if(app.productSlideCount!=0){
		View headerView = getLayoutInflater().inflate(R.layout.news_top, null);
		listView.addHeaderView(headerView);

		header.viewPager = (ViewPager) headerView
				.findViewById(R.id.news_top_vp);
		header.tv_title = (TextView) headerView
				.findViewById(R.id.news_top_title);
		header.viewPager.setAdapter(new TopAdapter());// 设置填充ViewPager页面的适配器
		header.viewPager.setOnPageChangeListener(new MyPageChangeListener());
		header.imageResId = new int[app.productSlideCount];
		header.titles = new String[app.productSlideCount];
		header.dots = new ArrayList<View>();
		header.dots.add(headerView.findViewById(R.id.news_top_dot0));
		header.dots.add(headerView.findViewById(R.id.news_top_dot1));
		header.dots.add(headerView.findViewById(R.id.news_top_dot2));
		header.dots.add(headerView.findViewById(R.id.news_top_dot3));
		header.dots.add(headerView.findViewById(R.id.news_top_dot4));
		header.dots.add(headerView.findViewById(R.id.news_top_dot5));
		header.dots.add(headerView.findViewById(R.id.news_top_dot6));
		header.dots.add(headerView.findViewById(R.id.news_top_dot7));
		header.dots.add(headerView.findViewById(R.id.news_top_dot8));
		header.dots.add(headerView.findViewById(R.id.news_top_dot9));

		for (int i : header.imageResId) {
			header.imageResId[i] = R.drawable.bg_view;
			header.titles[i] = "";
		}
		for (int i = header.imageResId.length; i < 10; i++) {
			header.dots.get(i).setVisibility(View.GONE);
		}
		header.imageViews = new ArrayList<ImageView>();

		// 初始化图片资源
		for (int i = 0; i < header.imageResId.length; i++) {
			ImageView imageView = new ImageView(Index4Activity.this);
			imageView.setImageResource(header.imageResId[i]);
			imageView.setScaleType(ScaleType.CENTER_CROP);
			header.imageViews.add(imageView);
		}
		
		header.tv_title = (TextView) headerView
				.findViewById(R.id.news_top_title);
		header.tv_title.setText(header.titles[0]);
		header.viewPager = (ViewPager) headerView
				.findViewById(R.id.news_top_vp);
		
		header.topadapter = new TopAdapter();
		header.viewPager.setAdapter(header.topadapter);// 设置填充ViewPager页面的适配器
		header.viewPager.setOnPageChangeListener(new MyPageChangeListener());
		}
		listView.setDivider(getResources().getDrawable(R.drawable.divider));
		listView.setSelector(getResources().getDrawable(
				R.drawable.list_item_colorexchange));
		listView.setDividerHeight(2);
		listView.setAdapter(adapter);
		listView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				loadDataTask();
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (((TradeApp) getApplicationContext()).isNetWorkConnection) {

					Intent intent3 = new Intent(Index4Activity.this,
							ProductInfoActivity.class);
					intent3.putExtra("productID", list_info.get(position - 1)
							.getPage_id());
					startActivity(intent3);

				} else {
					Toast toast2 = Toast.makeText(Index4Activity.this,
							"网络连接断开，请检查网络", Toast.LENGTH_SHORT);
					toast2.setGravity(Gravity.CENTER, 0, 0);
					toast2.show();
				}

			}
		});

		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int height = metric.heightPixels;
		float px = 64 * (metric.densityDpi / 160f);
		perPageCount = (int) Math.ceil(height / px);

		linear.addView(viewWhitProgress);

		Message msg0 = new Message();
		msg0.what = 0;
		handler.sendMessage(msg0);

	}

	private void loadDataTask() {
		currentPage = currentPage + 1;
		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "productList");
		if (!app.product_rating.equals("")) {
			map.put("city", app.product_rating.getCategory_id());
		}
		if (!app.product_rating.equals("")) {
			map.put("bySectorMin", app.product_rating.getCategory_id());
		}
		map.put("currentPage", String.valueOf(currentPage));
		map.put("rowCountPerPage", perPageCount + "");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				try {
					Log.d("TAG",response.toString());
					String succeed = response.getString("succeed");
					if (succeed.equals("000")) {
						
						String currentPage = response.getString("currentPage");
						String totalPage = response.getString("totalPage");
						
						if (currentPage.equals(totalPage)) {
							listView.loadComplete(false);
						}
						
						String data = response.getString("dataList");

						JSONArray list = new JSONArray(data);

						for (int i = 0; i < list.length(); i++) {
							ProductItemInfo info = new ProductItemInfo();
							JSONObject log = list.getJSONObject(i);
							info.setPage_id(log.getString("id"));
							info.setPage_icon(log.getString("photo"));
							info.setPage_name(log.getString("name"));
							info.setPage_price(log.getString("price"));
							info.setPage_categ(log.getString("productType"));
							info.setPage_comname(log.getString("companyName"));
							info.setPage_area(log.getString("city"));
							
							list_info.add(info);
						}
						

						JSONArray slideDataList = response
								.getJSONArray("slideData");
						header.imageViews.clear();
						for (int i = 0; i < slideDataList.length(); i++) {
							final JSONObject pic = slideDataList
									.getJSONObject(i);
							final String nid=pic.getString("id");
							ImageView imageView = new ImageView(
									Index4Activity.this);
							imageLoader.DisplayImage(URLHelper.mPrefixImg + "/"
									+ pic.getString("imgPath"), imageView,
									R.drawable.default_middle);
							imageView.setScaleType(ScaleType.CENTER_CROP);
							mHeaerID.add(nid);
							header.imageViews.add(imageView);
							header.titles[i] = pic.getString("name");
						}
						for (int i = slideDataList.length(); i < 10; i++) {
							ImageView imageView = new ImageView(
									Index4Activity.this);
							header.imageViews.add(imageView);
						}
						header.tv_title.setText(header.titles[0]);
						header.topadapter.notifyDataSetChanged();

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

				// We need notify the adapter that the data have been changed
				adapter.notifyDataSetChanged();
				viewWhitProgress.show();

			}

			@Override
			public void onFailure(Throwable e) {
				// TODO Auto-generated method stub

			}
		});

	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == header_left) {
			Intent intent = new Intent(Index4Activity.this,
					SearchActivity.class);
			intent.putExtra("index", "4");
			startActivity(intent);
		} else if (v == header_right) {

			expander = new ExpanderDialog(Index4Activity.this,
					new DialogListener() {

						@Override
						public void endme(String group, String value,
								int groupid, int valueid) {
							//
							header_right.setText(group + " " + value);
							app.product_rating
									.setCategory_id(app.cityids[groupid][valueid]);
							app.product_rating.setCategory_name(value);

							list_info.clear();
							currentPage = 0;
							totalPage = 0;
							perPageCount = 10 /* (int) Math.ceil(height / px) */;
							viewWhitProgress.loading();
							loadDataTask();
						}
					}, 1);
			expander.show();

			/*
			 * Intent intent = new Intent(Index4Activity.this,
			 * CategoryActivity.class); intent.putExtra("categ", "1");
			 * startActivity(intent);
			 */
		}

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (Constant.debug)
				Log.d("TMG", "ManageActivity KEYCODE_BACK");
			QuitDialog dialog = new QuitDialog(Index4Activity.this);
			dialog.exitConfirm();

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 当ViewPager中页面的状态发生改变时调用
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;

		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			currentItem = position;
			header.tv_title.setText(header.titles[position]);
			header.dots.get(oldPosition).setBackgroundResource(
					R.drawable.news_normal);
			header.dots.get(position).setBackgroundResource(
					R.drawable.news_focused);
			oldPosition = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	/**
	 * 填充ViewPager页面的适配器
	 * 
	 * @author Administrator
	 * 
	 */
	private class TopAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return header.imageResId.length;
		}

		@Override
		public Object instantiateItem(View collection, final int position) {
			/*((ViewPager) collection).addView(header.imageViews.get(position));
			Log.d("TAG", position + "");
			return header.imageViews.get(position);*/
			
			ImageView img = header.imageViews.get(position);
			img.setOnClickListener( new OnClickListener() {
                public void onClick(View m) {
                	Intent intent = new Intent(Index4Activity.this,
                			ProductInfoActivity.class);
					intent.putExtra("productID", mHeaerID.get(position));
					startActivity(intent);
	                }
	            });
			
			((ViewPager) collection).addView(img);
			return header.imageViews.get(position);
			
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {

			return arg0 == arg1;
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

	}

}